package com.guosheng.test20181219;

import java.util.ArrayList;
import java.util.List;

/**
 * 具体的主题对象
 */
public class ConcreteSubject implements Subject{

    List<Observer> mlist = new ArrayList<>();

    @Override
    public void addObserver(Observer observer) {
        //确保相同的观察者只有一个
        if(null == observer){
            throw new NullPointerException("observer == null");
        }
        if(!mlist.contains(observer)){
            mlist.add(observer);
        }
    }

    @Override
    public void removerObserver(Observer observer) {
        mlist.remove(observer);
    }

    @Override
    public void removeAll() {
        mlist.clear();
    }

    @Override
    public void notifyAllObserver(Object data) {
        for (Observer o : mlist){
            o.update(this,data);
        }
    }

    @Override
    public void notifyObserver(Observer observer, Object data) {
        if(null != observer){
            observer.update(this,data);
        }
    }
}
